# Python 趣味编程：第 2 章　
# 练习问题 2.1 启动“车”
# --------------------------
# 程序名: ex02-1-cars.py

from tkinter import *
from dataclasses import dataclass
import time

# 初始数据
DURATION = 0.01    # sleep时间=绘图的间隔
STEPS = 20000      # 帧数
RIGHT = 700        # 右侧的“折回”位置
LEFT = 100         # 左侧的“折回”位置

@dataclass
class Car:
    ids: list
    x: int
    y: int
    l: int
    h: int
    wr: int
    vx: int
    bcolor: str

# 把汽车画在初始位置上
def make_car(x, y, l, h, wr, vx, bcolor):
    #　坐标0,0,0,0表示虚拟值
    id0 = canvas.create_rectangle(0, 0, 0, 0,
                                  fill=bcolor, outline=bcolor)
    id1 = canvas.create_oval(0, 0, 0, 0,
                             fill="black", outline="black")
    id2 = canvas.create_oval(0, 0, 0, 0,
                             fill="black", outline="black")
    ids = [id0, id1, id2]
    return Car(ids, x, y, l, h, wr, vx, bcolor)

# 汽车的移动
def move_car(car):
  car.x += car.vx

# 汽车的重新绘制
def redraw_car(car):
    ids = car.ids
    x = car.x
    y = car.y
    l = car.l       # 车的长度
    h = car.h       # 车的高度
    wr = car.wr     # 轮胎的半径
    wh_1_x = x + l/4 - wr    # 前轮的中心位于整体的1/4位置
    wh_2_x = x + 3*l/4 - wr  # 后轮的中心位于整体的3/4位置
    wh_y = y + h - wr
    canvas.coords(ids[0], x, y, x + l, y + h)
    canvas.coords(ids[1], wh_1_x, wh_y, wh_1_x + 2*wr, wh_y + 2*wr)
    canvas.coords(ids[2], wh_2_x, wh_y, wh_2_x + 2*wr, wh_y + 2*wr)

# 程序正文
tk=Tk()
canvas = Canvas(tk, width=800, height=600, bd=0)
canvas.pack()
tk.update()

# 汽车数据
cars = [
    make_car(150, 100, 100, 50, 10, 1, "blue"),
    make_car(200, 250, 100, 70, 5, 2, "red"),
    make_car(250, 400, 200, 40, 10, 1, "orange"),
    ]

# 整个程序的循环
for s in range(STEPS):
    for car in cars:      # 对所有的汽车重复
        # 左边是下一个穿墙的
        if (car.x + car.vx <= LEFT \
           or car.x + car.l >= RIGHT):   # 如果右边穿墙
           car.vx = -car.vx    # 翻转移动方向
        move_car(car)     # 把车开动
        redraw_car(car)     # 反映绘图
    tk.update()           # 绘图反映在画面上
    time.sleep(DURATION)  # 在接下来的绘图之前，都要sleep
